import React from "react";
import { menuList } from "../../config";
import * as Icons from "@ant-design/icons";
import { Link, useNavigate } from "react-router-dom";
import { Layout, Menu } from "antd";
import { useDispatch } from "react-redux";
import { selectMenuList } from "../../store/reducers/tab";
import logoImg from "../../assets/images/user.jpg";
import type { AntdIconProps } from "@ant-design/icons/lib/components/AntdIcon";

const { Sider } = Layout;

// 修正后的图标组件类型
type IconComponentType = React.ForwardRefExoticComponent<
  AntdIconProps & React.RefAttributes<HTMLSpanElement>
>;

interface MenuItem {
  path: string;
  icon: string;
  label: string;
  children?: MenuItem[];
}

interface CommonSiderProps {
  collapsed: boolean;
}

const CommonSider: React.FC<CommonSiderProps> = ({ collapsed }) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 修正图标组件类型定义
  const IconElement = (iconName: string): IconComponentType => {
    const IconComponent = Icons[iconName as keyof typeof Icons];
    if (!IconComponent) {
      throw new Error(`无法找到图标组件: ${iconName}`);
    }
    return IconComponent;
  };

  // 使用正确的AntdIconProps类型
  const createIconElement = (iconName: string) => {
    const Icon = IconElement(iconName);
    return React.createElement<AntdIconProps>(Icon, {});
  };

  // 处理菜单项的转换
  const items = menuList.map((item: MenuItem) => {
    const menuItem = {
      key: item.path,
      icon: createIconElement(item.icon),
      label: item.label,
    };

    if (item.children) {
      menuItem.children = item.children.map((child) => ({
        key: child.path,
        icon: createIconElement(child.icon),
        label: child.label,
      }));
    }
    return menuItem;
  });

  const setMenuList = (val: { path: string; name: string; label: string }) => {
    dispatch(selectMenuList(val));
  };

  const handleRouterTO = (e: { key: string; keyPath: string[] }) => {
    let data: MenuItem | undefined;
    menuList.forEach((item: MenuItem) => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item;
        if (e.keyPath.length > 1 && item.children) {
          data = item.children.find((child: MenuItem) => child.path === e.key);
        }
      }
    });
    if (data) {
      setMenuList({
        path: data.path,
        name: data.path, // 假设 name 和 path 相同，否则需要根据实际情况调整
        label: data.label,
      });
      navigate(e.key);
    }
  };

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          height: 64,
          padding: "0 24px",
        }}
      >
        {collapsed ? (
          <h3 className="app-name">后台</h3>
        ) : (
          <>
            <Link to="/">
              <img
                src={logoImg}
                alt="logo"
                style={{ height: 40, width: 40, borderRadius: 50 }}
              />
            </Link>
            <h3 className="app-name">react-admin</h3>
          </>
        )}
      </div>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={["1"]}
        items={items}
        style={{
          height: "100%",
        }}
        onClick={handleRouterTO}
      />
    </Sider>
  );
};

export default CommonSider;
